package com.torches.cloud.controller;

import com.torches.cloud.beans.User;
import com.torches.cloud.entities.Msg;
import com.torches.cloud.service.UserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * @author torches
 */
@RestController
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**读取配置文件的云盘的基础目录*/
    @Value("${cloudDisk.baseDir}")
    private String cloudDiskBaseDir;

    /**登录*/
    @PostMapping("/login")
    public Msg login(@RequestBody  User  user){
        // 从数据库查询是否存在该用户
        User loginUser = userService.login(user);
        // 不等于null存在
        if (loginUser != null){
            // 返回用户头像，用户名，电话号码等信息
            HashMap<String,String> userInfoMap = new HashMap<>();
            userInfoMap.put("username",loginUser.getUsername());
            userInfoMap.put("profilePhoto",loginUser.getProfilePhoto());
            userInfoMap.put("phoneNumber",loginUser.getPhoneNumber());
            return Msg.getMsg(200,"登录成功").addData("user",userInfoMap);
        }else{
            return Msg.getMsg(401,"用户名或密码错误");
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Msg register(@RequestBody  User  user){
        System.out.println(user);
        boolean exist = userService.existUser(user);
        if (exist){
            return Msg.getMsg(401,"该用户已存在，请重新输入");
        } else{
            userService.addUser(user);
            // 未该用户新建目录
            File dir = new File(cloudDiskBaseDir + File.separator + user.getUsername());
            // 判断目录是否存在
            if (!dir.exists()) {
                dir.mkdir();
            }
            return Msg.getMsg(200,"注册成功");
        }
    }


    @RequestMapping(value = {"/img"}, method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    public String getProfilePhoto(
                          HttpServletResponse httpServletResponse,
                          @RequestParam("photo") String photo) throws IOException {
        // img为图片的二进制流
        String photoPath = cloudDiskBaseDir + File.separator + "profile" + File.separator + "ProfilePhoto" + File.separator + photo;

        httpServletResponse.setContentType("image/png");
        OutputStream os = httpServletResponse.getOutputStream();
        File photoFile = new File(photoPath);
        if (photoFile.exists()){
            FileUtils.copyFile(photoFile,os);
        }

        return "success";
    }
}